package com.dimld.connect.server;

import com.dimld.connect.MsgReaderI;
import com.dimld.connect.tcp.TcpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.RejectedExecutionException;

public class TcpServer implements Runnable {
    private final Logger   log = LoggerFactory.getLogger(TcpServer.class);
    private final int      port;
    private final Class<?> tcpMsgReader;
    private final int      timeout;
    private final String   serviceUUID;

    public TcpServer(int port, Class<?> tcpMsgReader, int timeout, String serviceUUID) {
        this.port = port;
        this.tcpMsgReader = tcpMsgReader;
        this.timeout = timeout;
        this.serviceUUID = serviceUUID;
    }

    public void run() {
        Thread.currentThread().setName("TcpServer");
        try {
            ServerSocket server = new ServerSocket(this.port);
            this.log.info("[TCP]启动TCP服务成功！使用端口：" + this.port);
            try {
                while (true) {
                    Socket     socket = server.accept();
                    MsgReaderI mr     = (MsgReaderI) this.tcpMsgReader.newInstance();
                    TcpClient  tc     = new TcpClient(socket, mr, true, timeout, serviceUUID);
                    Thread     th     = new Thread(tc);
                    th.start();
                }
            } catch (RejectedExecutionException e) {
                while (true)
                    this.log.error("[TCP]不再接受任务", e);
            } catch (IOException e) {
                this.log.error("[TCP]IO异常", e);
                server.close();
            } catch (Exception e) {
                this.log.error("[TCP]其他异常", e);
                server.close();
            }
        } catch (BindException e) {
            String msg = "[TCP]端口冲突，程序退出";
            System.out.println(msg);
            this.log.error(msg, e);
            System.exit(0);
        } catch (IOException e) {
            this.log.error("[TCP]连接异常", e);
        } catch (Exception e) {
            this.log.error("[TCP]其他异常", e);
        }
    }
}